<?php

namespace app\api\service\intelligentlive;

use app\api\model\intelligentlive\Account;
use app\api\model\intelligentlive\Device;
use app\lib\exception\intelligentlive\IntelligentliveException;
use think\Db;
use think\Exception;
use think\Request;

class DeviceService
{
    private static $instance;

    public static function getInstance(): DeviceService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function addDevice($params)
    {
        $info = [
            "device_name"=>$params['device_name'],
            "key"=>$params['key']??"",
            "start_time"=>$params['start_time']??"",
            "end_time"=>$params['end_time']??date("Y-m-d H:i:s", strtotime("+30 days", strtotime($params["start_time"]))),
        ];

        $device = Device::where("device_name",$params['device_name'])->findOrEmpty();
        if ($device){
            throw new intelligentliveException([
                'msg' => "设备已存在，请勿重复提交",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            Device::create($info);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new intelligentliveException([
                'msg' => "添加失败",
                'error_code' => 20002
            ]);
        }
    }

    public function upDevice($params)
    {
        $device = Device::where("id",$params['id'])->findOrEmpty();
        if (!$device->isEmpty()){
            $res = Device::update($params);
            if (!$res) {
                throw new intelligentliveException([
                    'msg' => "更新失败",
                    'error_code' => 20003
                ]);
            }
        } else {
            throw new intelligentliveException([
                'msg' => "设备不存在",
                'error_code' => 20003
            ]);
        }
        return true;
    }

    public function delDevice($params)
    {
        $info = Device::where("id",$params["id"])->findOrEmpty();
        if ($info->isEmpty()){
            throw new intelligentliveException([
                'msg' => '设备不存在',
                'error_code' => 20001
            ]);
        }
        $info->delete();
    }

    public function deviceList($params)
    {
        $pageSize = $params['pageSize']??200;
        $query = Device::field("*");
        if (!empty($params["key"])) {
            $query->where("key", $params["key"]);
        }
        $data = $query->paginate($pageSize);
        return $data;
    }
}